/*
 * Copyright (c) 2006-2022, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-27     THEWON       first version
 */

#include "board.h"
#include "drv_common.h"
#include "drv_sys.h"
#include "nuc970.h"
#include "nuc970_etimer.h"
#include "nu_miscutil.h"
#include "mmu.h"

#ifdef RT_USING_SERIAL
#include "drv_uartX.h"
#endif

#define SYSTICK_TIMER   0

/* Concatenate the macros of timer instance for driver usage. */
#define SYSTICK_TMR           CONCAT2(ETMR, SYSTICK_TIMER)
#define SYSTICK_IRQ           CONCAT2(SYSTICK_TMR, _IRQn)
#define SYSTICK_CLK           CONCAT2(SYS_CLKEN_ETIMER, SYSTICK_TIMER)

#define TIMER_DR              CONCAT2(CONCAT2(REG_ETMR, SYSTICK_TIMER), _DR)
#define TIMER_CMPR            CONCAT2(CONCAT2(REG_ETMR, SYSTICK_TIMER), _CMPR)

#if defined(BSP_USING_MMU)
static struct mem_desc hw_mem_desc[] =
{
	{ 0x00000000, 0xFFFFFFFF,     0x00000000, RW_NCNB },     /* None cached for 4G memory */
	{ 0x00000000, 0x04000000-1,   0x00000000, RW_CB   },     /* 64M cached DDR memory */
	{ 0x80000000, 0x84000000-1,   0x80000000, RW_CNB  },     /* Shadow DDR Map */
	{ 0x3C000000, 0x3C00E000-1,   0x3C000000, RW_NCNB },     /* 56K SRAM memory */
	{ 0xBC000000, 0xBC00E000-1,   0xBC000000, RW_NCNB }      /* 56K Shadow memory */
};
#endif

uint32_t SystickClock = 12000000;

#ifdef RT_USING_FINSH
#include <finsh.h>
static void reboot(uint8_t argc, char **argv)
{
    rt_hw_cpu_reset();
}
MSH_CMD_EXPORT(reboot, Reboot System);
#endif /* RT_USING_FINSH */

#if 0
static void ETMR0_IRQHandler(void)
{
    rt_tick_increase();
    ETIMER_ClearIntFlag(0);
}
#else
static void SYSTICK_IRQHandler(int vector, void *param)
{
    rt_tick_increase();
    ETIMER_ClearIntFlag(SYSTICK_TIMER);
}
#endif

void rt_hw_systick_irq_enable(void)
{
    // Enable timer interrupt
    ETIMER_EnableInt(SYSTICK_TIMER);

    ETIMER_Start(SYSTICK_TIMER);

    rt_hw_interrupt_umask(SYSTICK_IRQ);
}

/* SysTick configuration */
void rt_hw_systick_init(void)
{
    // Enable ETIMER0 engine clock
    outpw(REG_CLK_PCLKEN0, inpw(REG_CLK_PCLKEN0) | SYSTICK_CLK);

    // Set timer frequency to 1HZ
    ETIMER_Open(SYSTICK_TIMER, ETIMER_PERIODIC_MODE, RT_TICK_PER_SECOND);

#if 0
    sysInstallISR(HIGH_LEVEL_SENSITIVE | IRQ_LEVEL_1, ETMR0_IRQn, (PVOID)ETMR0_IRQHandler);
    sysEnableInterrupt(ETMR0_IRQn);
#else
    rt_hw_interrupt_install(SYSTICK_IRQ, SYSTICK_IRQHandler, RT_NULL, "systick");
    rt_hw_interrupt_set_priority(SYSTICK_IRQ, IRQ_LEVEL_7);
    rt_hw_interrupt_set_type(SYSTICK_IRQ, HIGH_LEVEL_SENSITIVE);
#endif

    SystickClock = ETIMER_GetModuleClock(SYSTICK_TIMER);

    rt_hw_systick_irq_enable();
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void _Error_Handler(char *s, int num)
{
    /* USER CODE BEGIN Error_Handler */
    /* User can add his own implementation to report the HAL error return state */
    while(1)
    {
    }
    /* USER CODE END Error_Handler */
}

/**
 * This function will delay for some us.
 *
 * @param us the delay time of us
 */
void rt_hw_us_delay(rt_uint32_t us)
{
    rt_uint32_t ticks;
    rt_uint32_t told, tnow, tcnt;
    rt_uint32_t reload;

    told = inpw(TIMER_DR);
    reload = inpw(TIMER_CMPR);
    ticks = SystickClock / 1000000UL * us;
    tcnt = 0;
    while (1) {
        tnow = inpw(TIMER_DR);

        if (tnow > told) {                  // increase timer
            tcnt += tnow - told;
        } else {
            tcnt += reload - told + tnow;
        }
        told = tnow;
        if (tcnt >= ticks) {
            break;
        }
    }
}

void rt_hw_board_init(void)
{
	/* initialize mmu */
#if defined(BSP_USING_MMU)
	rt_hw_mmu_init(&hw_mem_desc[0], sizeof(hw_mem_desc) / sizeof(hw_mem_desc[0]));
	rt_hw_cpu_dcache_enable();
	rt_hw_cpu_icache_enable();
#else
    /* disable I/D cache */
//    mmu_disable_dcache();
//    mmu_disable_icache();
//    mmu_disable();
//    mmu_invalidate_tlb();

    sysDisableCache();
    sysFlushCache(I_D_CACHE);
    sysEnableCache(CACHE_WRITE_BACK);
#endif

	/* initialize uart */
    sysInitializeUART();

	/* initialize timer0 */
	rt_hw_systick_init();

	/* init memory system */
#ifdef RT_USING_HEAP
	rt_system_heap_init(BOARD_HEAP_START, BOARD_HEAP_END);
#endif

    /* Pin driver initialization is open by default */
#ifdef RT_USING_PIN
    rt_hw_pin_init();
#endif

    /* USART driver initialization is open by default */
#ifdef RT_USING_SERIAL
    rt_hw_usart_init();
#endif

    /* Set the shell console output device */
#ifdef RT_USING_CONSOLE
//	rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif
}
